package com.dfrz.problem.dao.impl;

import java.util.Date;
import java.util.Iterator;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.dfrz.problem.dao.EmployeeDao;
import com.dfrz.problem.model.Employee;
import com.dfrz.problem.model.Role;
import com.dfrz.problem.utils.MD5Util;

public class EmployeeDaoImpl implements EmployeeDao {
	private static final Logger logger = LoggerFactory
			.getLogger(EmployeeDaoImpl.class);

	private SessionFactory sessionFactory;
	
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	public Session getSession() {
		return sessionFactory.getCurrentSession();
	}

	@Override
	public Employee getEmployee(String email) {
		String hql = "FROM Employee e JOIN FETCH e.role JOIN FETCH e.project WHERE e.employeeEmail =:email";
		Query query = getSession().createQuery(hql);

		query.setParameter("email", email);
		Employee employee = (Employee) query.uniqueResult();
		if (employee != null) {
			logger.debug("Employee -----> {}", employee.getEmployeeEmail());
		}

		return employee;
	}

	@Override
	public boolean addEmployee(Employee employee) {
		
		Employee queryEmployee = getEmployee(employee.getEmployeeEmail());
		// 不为空说明账户已经存在
		if (queryEmployee != null) {
			logger.debug("账户 {} 注册失败,原因是账户已存在!", employee.getEmployeeEmail());
			return false;
		}
		employee.setCreateTime(new Date());// 设置用户创建时间
		// 密码加密
		employee.setPassword(MD5Util.getMD5Str(employee.getPassword()));
		getSession().save(employee);
		logger.debug("新增员工账户:" + employee.getEmployeeEmail());

		return true;
	}

	@Override
	/**
	 * 通过用户名邮箱来删除员工信息
	 * @author WANG
	 */
	public boolean deleteEmployee(String email) {

		Employee queryEmployee = getEmployee(email);
		// 为空说明账户不存在即删除失败
		if (queryEmployee == null) {
			logger.debug("员工账户{}删除失败，因为不存在该账户！", email);
			return false;
		} else {
			// 根据用户名邮箱来删除员工信息
			String hql2 = "delete Employee p where p.employeeEmail=:email";
			Query query2 = getSession().createQuery(hql2);
			query2.setParameter("email", email);
			query2.executeUpdate();
			return true;

		}
	}

	@Override
	public boolean updateEmployee(Employee employee) {
		Employee queryEmployee = getEmployee(employee.getEmployeeEmail());
		if(queryEmployee == null){
			logger.debug("员工信息修改失败,邮箱 {} 不存在!",employee.getEmployeeEmail());
			return false;
		}
		
		getSession().clear();
		getSession().update(employee);
		logger.debug("账户 {} 个人信息更新成功!",employee.getEmployeeEmail());
		
		return true;
	}

	@Override
	public boolean checkPwd(String password, String email) {
		Employee queryEmployee = getEmployee(email);
		logger.debug("验证员工  {} 密码是否正确",email);
		if(queryEmployee != null){
			return queryEmployee.getPassword().equals(password);
		}
		
		return false;
	}

	@Override
	public boolean updatePwd(String email, String password) {
		String hql = "UPDATE Employee e SET e.password =:password WHERE e.employeeEmail =:email";
		Query query = getSession().createQuery(hql);
		
		query.setParameter("password", password);
		query.setParameter("email", email);
		// 更新一条数据
		return query.executeUpdate() == 1;
	}

	@Override
	public Employee getEmployeeOnProblemId(Integer problemId,Integer roleId) {
		String hql = "SELECT e FROM Employee e JOIN FETCH e.role LEFT JOIN e.problem p "
				+ "WHERE p.problemId =:problemId";
		Query query = getSession().createQuery(hql);
		query.setInteger("problemId", problemId);
		
		@SuppressWarnings("unchecked")
		Iterator<Employee> it = query.list().iterator();
		while(it.hasNext()){
			Employee employee = it.next();
			if(employee.getRole().getRoleId() == roleId){
				return employee;
			}
		}
		
		return null;
	}

	@Override
	public List<Employee> getListEmployee(Integer projectId) {
		String hql = "FROM Employee e WHERE e.project.projectId =:projectId";
		Query query = getSession().createQuery(hql);
		query.setInteger("projectId", projectId);
		@SuppressWarnings("unchecked")
		List<Employee> list = query.list();
		
		return list;
	}

	@Override
	public boolean giveroleEmployee(String email, Role role) {
		Employee queEmployee = getEmployee(email);
		if (queEmployee == null) {
			logger.debug("员工账户{}赋予角色失败，因为不存在该账户！",email);
			return false;
		}
		else {
			queEmployee.setRole(role);
			//存在该账户，根据应用户名邮箱和角色编号来赋予员工角色信息
//			String hql3 = "UPDATE Employee e SET e.roleId = role";
//			Query query3 = getSession().createQuery(hql3);
			getSession().update(queEmployee);
//			query3.setParameter("email", email); /////???????????????????????????
//			query3.executeUpdate();
			return true;
		}
	}

	@Override
	public List<Employee> getEmployeeAll() {
		String hql = "FROM Employee e";
		Query query = getSession().createQuery(hql);
		@SuppressWarnings("unchecked")
		List<Employee> list = query.list();
		
		return list;
	}

	@Override
	public Employee getEmployee(Integer employeeId) {
		String hql = "FROM Employee e JOIN FETCH e.role  WHERE e.employeeId =:employeeId";
		Query query = getSession().createQuery(hql);
		query.setInteger("employeeId", employeeId);
		return (Employee) query.uniqueResult();
	}

	@Override
	public boolean updateEmployeeProject(Employee employee) {
		getSession().update(employee);
		return true;
	}
}
